#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ford UK NGc2 爬虫模型数据抓取模块 - API版
专门使用Ford API获取车型信息，替代UI抓取的方式
移除了所有点击和页面抓取的复杂逻辑，直接调用API
"""

import time
import json
import requests
from selenium.webdriver.common.by import By
from .car_series import CarSeries
from .car_object import CarObject
from .car_extras import CarExtras


class ModelScraperAPI:
    """基于API的模型数据抓取器 - 简化版"""
    
    def __init__(self, driver, wait, page_utilities):
        """
        初始化模型抓取器
        
        Args:
            driver: WebDriver实例 (用于获取session cookies)
            wait: WebDriverWait实例 (保留兼容性)
            page_utilities: 页面工具类实例
        """
        self.driver = driver
        self.wait = wait
        self.page_utilities = page_utilities
    
    def scrape_model_data(self, config):
        """
        抓取车型数据的主方法 - API版
        
        Args:
            config: 配置信息
            
        Returns:
            CarSeries: 车系对象
        """
        print("📋 开始抓取车型数据 (API版)...")
        
        try:
            # 解析URL参数
            url = config['sub_model']['url']
            catalog_id, series_code, default_paint = self.page_utilities.parse_url_parameters(url)
            
            # 提取车系名称（从URL中推断）
            model_name = self._extract_model_name_from_url(url)
            
            # 创建车系对象
            car_series = CarSeries(
                car_series_name=model_name,
                catalog_id=catalog_id,
                series_code=series_code,
                default_paint=default_paint
            )
            
            print(f"车系信息: {model_name}, 目录ID: {catalog_id}, 车系代码: {series_code}")
            
            # 直接从API获取所有车型数据
            all_models = self._fetch_all_models_from_api(config)
            
            if not all_models:
                print("❌ API调用失败，未获取到车型数据")
                return car_series
            
            print(f"✅ 从API获取到 {len(all_models)} 个车型")
            
            # 创建CarObject实例
            self._create_car_objects(car_series, all_models, model_name)
            
            return car_series
            
        except Exception as e:
            print(f"❌ 抓取车型数据失败: {e}")
            return CarSeries(
                car_series_name="Focus",
                catalog_id=catalog_id if 'catalog_id' in locals() else "",
                series_code=series_code if 'series_code' in locals() else "",
                default_paint=default_paint if 'default_paint' in locals() else ""
            )
    
    def _fetch_all_models_from_api(self, config):
        """从Ford API获取所有车型数据"""
        try:
            print("🌐 正在从Ford API获取车型数据...")
            
            # 从配置文件读取API信息
            if 'api_endpoints' not in config:
                print("❌ 配置文件中未找到api_endpoints")
                return []
            
            api_config = config['api_endpoints']
            if 'vehicle_model' not in api_config or 'load' not in api_config['vehicle_model']:
                print("❌ 配置文件中未找到vehicle_model.load API配置")
                return []
            
            load_config = api_config['vehicle_model']['load']
            base_url = load_config['url']
            base_params = load_config['params']
            series_codes = load_config.get('series_codes', {})
            key_features_path = load_config.get('key_features_path', 'data.keyFeatures.walkup.combined.features')
            
            all_models = []
            
            # 为每个车型调用API
            for model_name, series_code in series_codes.items():
                print(f"  📡 获取 {model_name} ({series_code}) 的数据...")
                
                try:
                    # 构建请求参数
                    params = base_params.copy()
                    params['config'] = params['config'].replace('{SERIES_CODE}', series_code)
                    
                    # 获取session cookies
                    cookies = self._get_browser_cookies()
                    
                    # 发送API请求
                    response = requests.get(base_url, params=params, cookies=cookies, timeout=30)
                    
                    if response.status_code == 200:
                        data = response.json()
                        
                        # 提取Key Features
                        key_features = self._extract_key_features_from_response(data, key_features_path)
                        
                        # 提取价格信息
                        price = self._extract_price_from_response(data)
                        
                        model_data = {
                            'model_name': model_name,
                            'series_code': series_code,
                            'price': price,
                            'Key Features': key_features,
                            'raw_data': data  # 保存原始数据用于调试
                        }
                        
                        all_models.append(model_data)
                        print(f"    ✅ {model_name}: {len(key_features)} 个特性, 价格: {price}")
                        
                    else:
                        print(f"    ❌ {model_name}: API请求失败 (状态码: {response.status_code})")
                    
                    # 适当延迟，避免被限流
                    time.sleep(1)
                        
                except Exception as e:
                    print(f"    ❌ {model_name}: API调用异常: {e}")
                    continue
            
            return all_models
            
        except Exception as e:
            print(f"❌ 从API获取车型数据失败: {e}")
            return []
    
    def _get_browser_cookies(self):
        """从浏览器获取session cookies"""
        try:
            cookies = {}
            browser_cookies = self.driver.get_cookies()
            
            for cookie in browser_cookies:
                cookies[cookie['name']] = cookie['value']
            
            return cookies
            
        except Exception as e:
            print(f"⚠️ 获取browser cookies失败: {e}")
            return {}
    
    def _extract_key_features_from_response(self, data, key_features_path):
        """从API响应中提取Key Features"""
        try:
            # 按路径解析数据：data.keyFeatures.walkup.combined.features
            path_parts = key_features_path.split('.')
            current_data = data
            
            for part in path_parts:
                if isinstance(current_data, dict) and part in current_data:
                    current_data = current_data[part]
                else:
                    print(f"    ⚠️ 路径 {key_features_path} 在响应数据中不存在")
                    return []
            
            # 提取特性名称
            if isinstance(current_data, list):
                features = []
                for feature in current_data:
                    if isinstance(feature, dict):
                        # 尝试多个可能的字段名
                        name = (feature.get('name') or 
                               feature.get('title') or 
                               feature.get('description') or 
                               feature.get('label', ''))
                        if name:
                            features.append(name)
                    elif isinstance(feature, str):
                        features.append(feature)
                
                return features
            else:
                print(f"    ⚠️ Key Features数据格式不是列表: {type(current_data)}")
                return []
                
        except Exception as e:
            print(f"    ❌ 提取Key Features失败: {e}")
            return []
    
    def _extract_price_from_response(self, data):
        """从API响应中提取价格信息"""
        try:
            # 尝试多个可能的价格字段
            price_paths = [
                'data.prices.listPrice',
                'data.price.base',
                'data.pricing.total',
                'prices.listPrice',
                'price'
            ]
            
            for path in price_paths:
                try:
                    path_parts = path.split('.')
                    current_data = data
                    
                    for part in path_parts:
                        if isinstance(current_data, dict) and part in current_data:
                            current_data = current_data[part]
                        else:
                            break
                    else:
                        # 路径成功解析到最后
                        if isinstance(current_data, (int, float, str)):
                            return str(current_data)
                        elif isinstance(current_data, dict):
                            # 可能包含价格和货币信息
                            amount = current_data.get('amount') or current_data.get('value')
                            currency = current_data.get('currency', '£')
                            if amount:
                                return f"{currency}{amount}"
                except:
                    continue
            
            print("    ⚠️ 未找到价格信息")
            return "价格待查询"
                
        except Exception as e:
            print(f"    ❌ 提取价格失败: {e}")
            return "价格待查询"
    
    def _extract_model_name_from_url(self, url):
        """从URL中提取车型名称"""
        try:
            # 从URL中提取Focus等车型名称
            if 'focus' in url.lower():
                return 'Focus'
            elif 'fiesta' in url.lower():
                return 'Fiesta'
            elif 'mustang' in url.lower():
                return 'Mustang'
            else:
                return 'Unknown'
        except:
            return 'Unknown'
    
    def _create_car_objects(self, car_series, all_models, model_name):
        """创建CarObject实例"""
        try:
            for model_data in all_models:
                model_name_str = model_data.get('model_name', 'Unknown')
                price = model_data.get('price', '价格待查询')
                key_features = model_data.get('Key Features', [])
                
                print(f"创建车款实体类: {model_name_str}")
                
                # 创建车款实体类
                car_object = CarObject(
                    series_name=model_name,  # 车系名
                    model_name=model_name_str,  # 车款名
                    price=price,
                    drive=""  # 暂时为空，可以从API获取
                )
                
                # 添加Key Features
                for feature in key_features:
                    if feature and feature.strip():  # 只添加非空的特性
                        car_object.add_key_feature(feature)
                
                # 添加一些默认的颜色（作为示例）
                car_object.add_color("red")
                car_object.add_color("blue")
                car_object.add_color("yellow")
                
                # 添加示例选装件
                extra1 = CarExtras("Blind Spot Information System", "$1234")
                extra2 = CarExtras("Driver Assist Pack", "$575")
                car_object.add_extra(extra1)
                car_object.add_extra(extra2)
                
                # 添加到车系
                car_series.add_car_object(car_object)
            
            print(f"✅ 成功创建 {car_series.get_car_objects_count()} 个CarObject实例")
            
        except Exception as e:
            print(f"❌ 创建CarObject实例失败: {e}")
